# -*- coding: utf-8 -*-
import json
from datetime import datetime, timedelta
import math

from scrapy.utils.project import get_project_settings

from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.pipelines.helper.supplier_helper import SupplierHelper
from zc_core.util.http_util import fill_link
from zc_core.util.encrypt_util import md5
from zc_core.util.common import parse_time, parse_number

sp_helper = SupplierHelper()


# -------------------------------
def parse_shop_list(response):
    sp_list = list()
    rows = json.loads(response.text)
    for row in rows:
        supplier = Supplier()
        supplier['id'] = str(row.get('id'))
        supplier['name'] = row.get('name', '')
        supplier['code'] = row.get('code', '')
        sp_list.append(supplier)

    return sp_list


def parse_shop_cat(response):
    meta = response.meta
    sp_id = meta.get('supplierId')

    cat_list = list()
    rows = json.loads(response.text)
    for row in rows:
        cat = Catalog()
        cat['catalogId'] = str(row.get('id'))
        cat['catalogName'] = row.get('name', '')
        cat['catalogCode'] = str(sp_id)
        cat['level'] = row.get('level', '')
        cat_list.append(cat)

    return cat_list


def parse_sku_list(response):
    meta = response.meta
    sp_id = meta.get('supplierId')
    sp_name = meta.get('supplierName')
    cat_id = meta.get('catalogId')
    cat_name = meta.get('catalogName')

    sku_list = list()
    rows = json.loads(response.text)
    for row in rows:
        item = ItemData()
        item['skuId'] = str(row.get('id'))
        item['skuName'] = row.get('pname')
        item['salePrice'] = row.get('price') / 100
        item['supplierId'] = str(sp_id)
        item['supplierName'] = sp_name
        item['catalog1Id'] = cat_id
        item['catalog1Name'] = cat_name
        item['supplierSkuId'] = str(row.get('pid'))
        # item['stock'] = row.get('inventory', 0)

        sp_helper.fill(item)
        sku_list.append(item)

    return sku_list


def parse_item_data(response):
    meta = response.meta
    sku_id = meta.get('skuId')

    row = json.loads(response.text)
    item = ItemDataSupply()
    item['skuId'] = str(sku_id)
    item['salePrice'] = row.get('price') / 100
    item['stock'] = row.get('inventory', 0)

    return item
